/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package data;

import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import java.awt.image.WritableRaster;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;

import config.Debug;
import config.Settings;

/**
 * 
 * @author Yang Wang &lt;yang@digitalmenubox.com&gt;
 */
public class HttpPostConnector {

	private String result = null;
	private URL url = null;
	private String data;

	public static String getBoxToken() {
		return "menuboxid=" + Settings.getBoxId() + "&updatetoken=" + Settings.UPDATE_CHECKER_URL_TOKEN + "&version=" + Settings.VERSION;
	}

	public HttpPostConnector(URL url, String data) {
		this.url = url;
		this.data = data;
	}


	
	
	public boolean post() {
		if (!config.Helper.hasNetworkConnection()) {
			return false;// if no network, do nothing
		}

		boolean rtr = false;
		HttpURLConnection conn = null;
		OutputStreamWriter wr = null;
		BufferedReader rd = null;
		try {
			// Construct data
			if (this.data == null) {
				this.data = "";
			}
			// Send data
			URL url = this.url;
			conn = (HttpURLConnection) url.openConnection();
			conn.setDoOutput(true);
			wr = new OutputStreamWriter(conn.getOutputStream());
			wr.write(data);
			wr.flush();
			// Get the response
			if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
				rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
				// System.out.println(conn.getResponseCode() + " " +
				// conn.getResponseMessage());
				String line;
				StringBuilder sb = new StringBuilder();
				while ((line = rd.readLine()) != null) {
					sb.append(line);
				}
				this.result = sb.toString();
				wr.close();
				rd.close();
				conn.disconnect();
				rtr = true;
			} else {
				Debug.log("http connection failed " + conn.getResponseCode() + " " + conn.getResponseMessage(), Debug.EXCEPTION_LEVEL);
				Debug.msg("http connection failed " + conn.getResponseCode() + " " + conn.getResponseMessage());
			}
		} catch (Exception e) {
		}
		return rtr;
	}

	public synchronized String getResult() {
		return this.result;
	}

	public static void main(String[] args) throws MalformedURLException, InterruptedException {
		HttpPostConnector c = new HttpPostConnector(new URL("http://localhost/player/weather.php"), null);
		c.post();
		// System.out.println(c.getResult());
		String[] array = c.getResult().split(",");
		System.out.println(Arrays.toString(array));
		System.out.println(array.length);
		// can test the result here
	}
}
